import appConfig from 'AppConfig/index';
import * as common from "Commons/index";
import Api from 'Api/index';
import dayjs from 'dayjs';
import relativeTime from 'Utils/dayjs/relativeTime.min';
import "Utils/dayjs/zh-cn";
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');


/**
 * 下载
 * @param {*} url
 * @param {*} count
 * @returns
 */
export const wxDownloadFile = function(url,count=3){
    console.log(url)
    return new Promise((resolev,reject)=>{
        downloadFile(resolev,reject)
    })
    function downloadFile(resolev,reject){
        console.log(url)
        wx.downloadFile({
            url: url, //仅为示例，并非真实的资源
            success (res) {
                console.log('res',res)
                if(res.statusCode==200){
                    resolev(res.tempFilePath)
                }else{
                    if(count<=0){
                        resolev('')
                    }else{
                        downloadFile(resolev,reject)
                        count--
                    }
                }
            },
            fail(res){
                console.log('fail',res)
                if(count<=0){
                    resolev('')
                }else{
                    downloadFile(resolev,reject)
                    count--
                }
            }
        })
    }
}

/**
 * 复制内容
 * @param {*} data
 */
export const copyData = function(data) {
    wx.setClipboardData({
        data: data,
        success: function(res) {
            wx.getClipboardData({
                success: function(res) {}
            })
        }
    })
}
/**
 * 获取列表的全部元素 定义下吧 0-len
 * @param {列表的长度} len
 * @returns
 */
export const wxCreateSelectorQuery = function(select,len){
    return new Promise(async (resolveBack,rejectBack)=>{
        let list = [];
        for(let i=0;i<len;i++){
            let obj = await getViewSelectorReact(select+i)
            list.push(obj)
        }
        resolveBack(list)
    })
}
/**
 * 时间多久之前
 * @param {*} data 
 * @returns 
 */
export const timeFromNow = function (time){
    if( !time ) return '';
    return dayjs(time).fromNow();
}
/**
 * 获取元素的高度
 * @param {*} id
 * @param {*} q
 * @returns
 */
export const getViewSelectorReact = function(id,q){
    return new Promise((resolev,reject)=>{
        var query = wx.createSelectorQuery();
        query.select(id).boundingClientRect()
        query.exec(function(res) {
            var result = res[0]||{};
            if(q){
                resolev(result[q])
            }else{
                resolev(result)
            }
        })
    })
}
/**
 * 获取元素距离顶部
 * @param {*} selset
 * @returns
 */
export const getSelectTop = function(selset){
    return new Promise((resolve,reject)=>{
        wx.createSelectorQuery().select(`${selset}`).boundingClientRect((res)=>{
            resolve(res.top)
        }).exec();
    })
}

export const getMenuButtonBoundingClientRect = function(){
    return new Promise((resolve,reject)=>{
        const res = wx.getMenuButtonBoundingClientRect()
        resolve(res)
    })
}

/**
 * 查看图片
 * @param {*} urls
 * @param {*} current
 */
export const wxPreviewImage = function(urls,current){
    wx.previewImage({
      current: urls[current], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
}
/**
 * 选择文件资源
 */
export const wxChooseMessageFile = function(opt={}){
    return new Promise(function (resolve) {
        wx.chooseMessageFile({
            count: opt.count||1,
            type: "file",
            success: async (res)=> {
                let tempFiles = res.tempFiles;
                wx.hideLoading();
                resolve({
                    type: res.type,
                    result: tempFiles,
                });
            },
            fail:(res)=> {
                wx.hideLoading();
                resolve({})
            },
        });
    });
}
/**
 * 是否携带参数
 * @param {*} param
 * @returns
 */
export const getCurrentPage = function (param=true){
    let _getCurrentPages = getCurrentPages()||[];
    let _Pages = _getCurrentPages[_getCurrentPages.length-1]||{};
    let _route = _Pages.route;
    let _parameter = urlEncode(_Pages.options).slice(1);
    let pagesUrl = param ? (_route+(_parameter?'?'+_parameter:_parameter)) : _route;
    return pagesUrl;
}

// obj转url参数
export const urlEncode = function(param, key, encode) {
    if (param==null) return '';
    var paramStr = '';
    var t = typeof (param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += '&' + key + '='  + ((encode==null||encode) ? encodeURIComponent(param) : param);
    } else {
        for (var i in param) {
            var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
            paramStr += urlEncode(param[i], k, encode)
        }
    }
    return paramStr;
}

export const reloadPage = () => {
    const currentPages = getCurrentPages()
    const {onLoad, options} = currentPages[currentPages.length - 1]
    onLoad(options)
}
// 资源路径拼接
export const getUrlPath = function (url, type){
    if( !url ) return '';
    return url.indexOf('http')!=-1 ? url : (appConfig.ossPath+(url.indexOf('?')!=-1?url+'&':url+'?')+'v=20231129'+(type=='video'?'':''));
}
// 微信头像
export const wxHeadimgurl = function (wxHeadimgurl){
    return getUrlPath(wxHeadimgurl||appConfig[appConfig.envVersion].serverPath+'weapp/static/pages/headimg.png?type=default');
}

// 微信昵称
export const wxNickname = function (wxNickname){
    return wxNickname||'匿名用户';
}

// 获取小程序标签传值
export const getWxElementValue = function(e, name){
    let currentTarget = e.currentTarget||{};
    let dataset = currentTarget.dataset||{};
    return dataset[name]||'';
}

// 查找字符串中，指定字符的位置
export const find = function(str, cha, num) {
    let x = str.indexOf(cha);
    for( var i=0;i<num;i++ ){
        x = str.indexOf(cha,x+1);
    }
    return x;
}

// 获得百分比
export const getPercent = function(num, total) {
    /// <summary>
    /// 求百分比
    /// </summary>
    /// <param name="num">当前数</param>
    /// <param name="total">总数</param>
    num = parseFloat(num);
    total = parseFloat(total);
    if (isNaN(num) || isNaN(total)) {
        return "-";
    }
    total = total <= 0 ? 0 : (Math.round(num / total * 10000) / 100.00)
    return total>100?100:total;
}

// 时间格式
export const getDateText = (leftTime)=>{
    let d = Math.floor(leftTime/1000/60/60/24);  
    let h = Math.floor(leftTime/1000/60/60%24);
    let m = Math.floor(leftTime/1000/60%60);  
    let s = Math.floor(leftTime/1000%60);
    if( d>=1||h>=23 ){
        // 天
        return (d+1)+'天';
    }else if( h>=1||m>=59 ){
        // 小时
        return (h+1)+'小时';
    }else{
        // 分钟
        return (m+1)+'分钟';
    }
}

// 图片缩放尺寸计算
export const imageScale = function(w, h, maxW, maxH){ 
    let scale = maxW/w;
    let _maxW = w*scale;
    let _maxH = h*scale;
    if( maxH&&_maxH>maxH ){
        // 计算最大高度
        console.log('计算最大高度',_maxW,_maxH);
        scale = maxH/_maxH;
        _maxW = _maxW*scale;
        _maxH = _maxH*scale;
    }
    return {
        width: Math.round(_maxW),
        height: Math.round(_maxH),
    }
}

// 选择上传文件
export const chooseMediaUpload=function(opt={}){
    return new Promise((resolve)=>{
        wx.chooseMedia({
            count: opt.count||9,
            mediaType: opt.mediaType||['image', 'video'],
            sourceType: opt.sourceType||['album', 'camera'],
            maxDuration: opt.maxDuration||30,
            sizeType: opt.sizeType||['compressed'],
            camera: 'back',
            success: async (res)=>{
                console.log(res);
                let tempFiles = res.tempFiles||[];
                if( res.type=='image' ){
                    // 图片类型
                    let imgArr = [];
                    tempFiles.forEach(obj=>{
                        imgArr.push(new Promise(async (resolve, reject)=>{
                            let compressImageRes = await compressImage(obj.tempFilePath);
                            wx.getImageInfo({
                                src: obj.tempFilePath,
                                success: (res)=>{
                                    obj.tempFilePath = compressImageRes.tempFilePath;
                                    obj.height = res.height;
                                    obj.width = res.width;
                                    resolve(obj);
                                }
                            })
                        }));
                    });
                    tempFiles = await Promise.all(imgArr);
                }else if( res.type=="video" ){
                    // 视频类型

                }
                resolve(tempFiles);
            }
        });
    });
}

// 压缩图片
export const compressImage = function (src,quality=70){    
    return new Promise((resolve, reject)=> {
        if( src.indexOf('.png')!=-1 ){
            resolve({tempFilePath:src});
        }else{
            wx.compressImage({
                src: src,
                quality: quality, // 压缩质量
                success:(res)=> {
                    resolve(res);
                }
            })
        }
    });
}

// 上传图片文件
export const uploadImageFile = function (files){
    console.log('files',files);
    let promiseAll = [];
    files.forEach(filePath=>{
        promiseAll.push(new Promise(resolve=>{
            Api.ossSign({
                code: 'ugc',
                type: 'jpg',
            }).then(res=>{
                let ossSignInfo = res.result||{};
                if( !ossSignInfo.path ){
                    // 上传失败
                    resolve({
                        img_url: filePath,
                        img_url2: '',
                    });
                    return;
                }
                wx.uploadFile({
                    url: ossSignInfo.host,
                    filePath: filePath,
                    name: 'file',
                    formData: {
                        OSSAccessKeyId: ossSignInfo.accessid,
                        callback: ossSignInfo.callback,
                        policy: ossSignInfo.policy,
                        signature: ossSignInfo.signature,
                        key: ossSignInfo.path,
                        success_action_status: '200',
                        secure: true,
                    },
                    complete: (res)=> {
                        res = JSON.parse(res.data||"{}").result||{};
                        let url = res.url;
                        resolve({
                            img_url: filePath,
                            img_url2: url||'',
                        });
                    }
                });
            });
        }));        
    }); 
    return Promise.all(promiseAll); 
}

// 上传视频文件
export const uploadVideoFile = function (files){
    console.log('files',files);
    let promiseAll = [];
    files.forEach(filePath=>{
        promiseAll.push(new Promise(resolve=>{
            Api.ossSign({
                code: 'ugc',
                type: 'mp4',
            }).then(res=>{
                let ossSignInfo = res.result||{};
                if( !ossSignInfo.path ){
                    // 上传失败
                    resolve({
                        img_url: filePath,
                        img_url2: '',
                    });
                    return;
                }
                wx.uploadFile({
                    url: ossSignInfo.host,
                    filePath: filePath,
                    name: 'file',
                    formData: {
                        OSSAccessKeyId: ossSignInfo.accessid,
                        callback: ossSignInfo.callback,
                        policy: ossSignInfo.policy,
                        signature: ossSignInfo.signature,
                        key: ossSignInfo.path,
                        success_action_status: '200',
                        secure: true,
                    },
                    complete: (res)=> {
                        res = JSON.parse(res.data||"{}").result||{};
                        let url = res.url;
                        resolve({
                            img_url: filePath,
                            img_url2: url||'',
                        });
                    }
                });
            });
        }));        
    }); 
    return Promise.all(promiseAll); 
}

// ugc评论数据处理
export const ugcCommentMapData = function (item){
    item.time = timeFromNow(item.created_at);
    item.member.headimgurl = wxHeadimgurl(item.member.headimgurl);
    item.imgs = (item.imgs||[]).map(img=>{
        return getUrlPath(img);
    });
    if( item.child_comment ){
        item.child_comment.forEach(obj=>{
            obj.member.headimgurl = wxHeadimgurl(obj.member.headimgurl);
            obj.reply_member.headimgurl = wxHeadimgurl(obj.reply_member.headimgurl);
        });
    }
    return item;
}

// ugc数据处理
export const ugcMapData = function (item){
    item.member.headimgurl = wxHeadimgurl(item.member.headimgurl);
    item.imgs = item.imgs||[];
    item.time = timeFromNow(item.created_at);
    item.time2 = dayjs(item.created_at).format('YYYY-MM-DD');
    item.content = item.content.map(obj=>{
        obj.videoUrl = getUrlPath(obj.videoUrl);
        obj.img = getUrlPath(obj.img);
        if( obj.img ){
            // 没有封面，选择内容第一张作为封面
            if( !item.cover_img ){
                item.cover_img = obj.img;
            }
            item.imgs.push({
                img_url: obj.img,
                width: obj.width,
                hieght: obj.hieght,
            });
        }
        return obj;
    });
    item.cover_img = getUrlPath(item.cover_img);
    if( item.type==3 ){
        // 问答轮播
        let swiperBannerList = [];
        let swiperimgMaxHeight = 0;
        item.content.forEach(item=>{                            
            if( item.img ){
                let imgInfo = imageScale(Number(item.width), Number(item.height), 670, 920);
                item.width = imgInfo.width;
                item.height = imgInfo.height;                               
                if( item.height>swiperimgMaxHeight ){
                    swiperimgMaxHeight = item.height;
                }
                swiperBannerList.push(item);
            }
        });
        item.swiperimgMaxHeight = swiperimgMaxHeight;
        item.swiperBannerList = swiperBannerList;
    }else if( item.type==4 ){
        // 投票
        item.vote = item.vote||[];
        item.voteInfo = {
            options: item.vote.map(item=>{
                item.speed = 0;
                return item;
            }),
            isEnd: false,
            endTimeText: '',
            total: 0,
            selectedOptionId: 0,
        }
        item.voteInfo.options&&item.voteInfo.options.forEach(obj=>{
            item.voteInfo.total+=obj.selected_num;
            // 已经答题
            if( obj.selected==1 ){
                item.voteInfo.selectedOptionId = obj.id;
            }
        });
        item.voteInfo.options&&item.voteInfo.options.forEach(obj=>{
            obj.speed = getPercent(obj.selected_num, item.voteInfo.total);
        });
        // 剩余时间
        let _voteStartAt = dayjs(item.vote_start_at||item.created_at).valueOf();
        let _voteEndAt = dayjs(item.vote_end_at).valueOf();
        if( item.timestamp>_voteEndAt ){
            // 已经结束
            item.voteInfo.isEnd = true;
        }else{
            item.voteInfo.endTimeText = getDateText(_voteEndAt-item.timestamp);
        }
    }
    return item;
};